package com.ft.scan.controller;

import com.ft.scan.DTO.NLPRequestDTO;
import com.ft.scan.DTO.RequestDTO;
import com.ft.scan.DTO.RequestImgDTO;
import com.ft.scan.common.Result;
import com.ft.scan.common.TextInResult;
import com.ft.scan.domain.User;
import com.ft.scan.service.ITextInService;
import com.ft.scan.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ft/textin")
@Api(tags = "text in管理接口")
public class TextInController {
    
    @Autowired
    private IUserService userService;

    @Autowired
    private ITextInService textInService;

    @ApiOperation(value = "图片表格识别", notes = "将Base64编码的图片表格识别生成excel文件")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/photo_to_excel")
    public Result PhotoTOExcel(@RequestBody RequestDTO request) {

        // 获取请求体中传递的参数
        Long userId = request.getUserId();
        String base64ImageData = request.getBase64Data();
        // 获取base64编码的图片数据，这里需要进行异常处理，确保传入的数据是有效的Base64编码
        byte[] imgData;
        try {
            imgData = Base64.getDecoder().decode(base64ImageData);
        } catch (IllegalArgumentException e) {
            return Result.fail("图片数据格式不正确");
        }

        // 如果格式没有问题，检查用户是否具有足够的token
        User user = userService.selectUserByUserId(userId);
        if (user != null) {
            if (user.getToken() > 0) {
                user.setToken(user.getToken() - 1);
                TextInResult textInResult = textInService.photo_to_excel(imgData, userId);
                if (textInResult.getCode() == 200 && userService.updateUser(user) == 1) {

                    return Result.ok(textInResult.getData());
                } else {
                    return Result.fail(textInResult.getCode(), textInResult.getMessage());
                }
            } else return Result.fail("调用次数不足");
        }
        return Result.fail("用户不存在");
    }

    @ApiOperation(value = "证件分类", notes = "识别证件的类型，返回识别结果")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/cert_classify")
    public Result CertClass(@RequestBody RequestDTO request) {

        // 获取请求体中传递的参数
        Long userId = request.getUserId();
        String base64ImageData = request.getBase64Data();
        // 获取base64编码的图片数据，这里需要进行异常处理，确保传入的数据是有效的Base64编码
        byte[] imgData;
        try {
            imgData = Base64.getDecoder().decode(base64ImageData);
        } catch (IllegalArgumentException e) {
            return Result.fail("图片数据格式不正确");
        }

        // 如果格式没有问题，检查用户是否具有足够的token
        User user = userService.selectUserByUserId(userId);
        if (user != null) {
            if (user.getToken() > 0) {
                user.setToken(user.getToken() - 1);
                TextInResult textInResult = textInService.cert_classify(imgData);
                if (textInResult.getCode() == 200 && userService.updateUser(user) == 1) {
                    // 返回识别结果
                    return Result.ok(textInResult.getData());
                } else {
                    return Result.fail(textInResult.getCode(), textInResult.getMessage());
                }
            } else {
                return Result.fail("调用次数不足");
            }
        }
        return Result.fail("用户不存在");
    }

    @ApiOperation(value = "信息提取", notes = "识别文档中的信息")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = NLPRequestDTO.class)
    @PostMapping("/contents_extract")
    public Result ContentsExtract(@RequestBody NLPRequestDTO request) {

        // 获取请求体中传递的参数
        Long userId = request.getUserId();
        String base64ImageData = request.getBase64Data();
        String keys = request.getKeys();
        String type = request.getType();
        Integer pageNum = request.getPageNum();

        // 如果格式没有问题，检查用户是否具有足够的token
        User user = userService.selectUserByUserId(userId);
        if (user != null) {
            if (user.getToken() > pageNum) {
                user.setToken(user.getToken() - pageNum);
                TextInResult textInResult = textInService.contents_extract(base64ImageData, keys, type);
                if (textInResult.getCode() == 200 && userService.updateUser(user) == 1) {
                    return Result.ok(textInResult.getData());
                } else {
                    return Result.fail(textInResult.getCode(), textInResult.getMessage());
                }
            } else {
                return Result.fail("调用次数不足");
            }
        }
        return Result.fail("用户不存在");
    }


    @ApiOperation(value = "书籍扫描")
    @PostMapping("/scan_book")
    public Result scanBook(
            @ApiParam(name = "userId", value = "用户ID", required = true) Long userId,
            @ApiParam(name = "images", value = "多张书本的照片", required = true) String[] images,
            @ApiParam(name = "keys", value = "提取字段", required = true) String keys) {
        User user = userService.selectUserByUserId(userId);
        int imagesCount = images.length;

        if (user != null) {
            if (user.getToken() > imagesCount) {
                user.setToken(user.getToken() - imagesCount);
                TextInResult textInResult = textInService.scan_book(images, keys);
                if (textInResult.getCode() == 200 && userService.updateUser(user) == 1) {
                    return Result.ok(textInResult.getData());
                } else {
                    return Result.fail(textInResult.getCode(), textInResult.getMessage());
                }
            } else {
                return Result.fail("调用次数不足");
            }
        }
        return Result.fail("用户不存在");

    }

    protected Result PdfDeal(@RequestBody RequestDTO request, String type) {
        Long userId = request.getUserId();
        String base64Data = request.getBase64Data();
        byte[] pdfData = null;

        try {
            pdfData = Base64.getDecoder().decode(base64Data);
        } catch (IllegalArgumentException e) {
            return Result.fail("pdf数据格式不正确");
        }

        User user = userService.selectUserByUserId(userId);
        if (user != null) {
            if (user.getToken() > 0) {
                user.setToken(user.getToken() - 1);
                TextInResult textInResult = null;
                switch (type) {
                    case "word": {
                        textInResult = textInService.pdfToWord(pdfData, userId);
                        break;
                    }
                    case "ppt": {
                        textInResult = textInService.pdfToPPT(pdfData, userId);
                        break;
                    }
                    case "excel": {
                        textInResult = textInService.pdfToExcel(pdfData, userId);
                        break;
                    }
                    case "jpg": {
                        textInResult = textInService.pdfToJPG(pdfData, userId);
                        break;
                    }
                    case "wordToPDF": {
                        textInResult = textInService.wordToPDF(pdfData, userId);
                        break;
                    }
                    case "excelToPDF": {
                        textInResult = textInService.excelToPdf(pdfData, userId);
                        break;
                    }
                    case "wordToImg": {
                        textInResult = textInService.wordToImg(pdfData, userId);
                        break;
                    }
                    case "imgToWord": {
                        textInResult = textInService.photo_to_word(pdfData, userId);
                        break;
                    }
                    default: {
                        return Result.fail("不支持的文件类型");
                    }
                }
                return textInResult.getCode() == 200 && userService.updateUser(user) == 1 ? Result.ok(textInResult.getData()) :
                        Result.fail(textInResult.getCode(), textInResult.getMessage());
            } else {
                return Result.fail("调用次数不足");
            }
        }

        return Result.fail("用户不存在");
    }

    @ApiOperation(value = "PDF转Word", notes = "将PDF文件转换为Word文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/pdf-to-word")
    public Result PdfToWord(@RequestBody RequestDTO request) {
        return PdfDeal(request, "word");
    }

    @ApiOperation(value = "PDF转Excel", notes = "将PDF文件转换为Excel文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/pdf-to-excel")
    public Result PdfToExcel(@RequestBody RequestDTO request) {
        return PdfDeal(request, "excel");
    }

    @ApiOperation(value = "PDF转PPT", notes = "将PDF文件转换为PPT文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/pdf-to-ppt")
    public Result PdfToPPT(@RequestBody RequestDTO request) {
        return PdfDeal(request, "ppt");
    }

    @ApiOperation(value = "PDF转JPG", notes = "将PDF文件转换为JPG文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/pdf-to-jpg")
    public Result PdfToJPG(@RequestBody RequestDTO request) {
        return PdfDeal(request, "jpg");
    }

    @ApiOperation(value = "WORD转PDF", notes = "将WORD文件转换为PDF文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("word-to-pdf")
    public Result wordToPDF(@RequestBody RequestDTO request) {
        return PdfDeal(request, "wordToPDF");
    }

    @ApiOperation(value = "EXCEL转PDF", notes = "将EXCEL文件转换为PDF文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("excel-to-pdf")
    public Result excelToPdf(@RequestBody RequestDTO request) {
        return PdfDeal(request, "excelToPDF");
    }

    @ApiOperation(value = "图片集合转PDF", notes = "将图片集合转换为PDF文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestImgDTO.class)
    @PostMapping("image-to-pdf")
    public Result photoToPdf(@RequestBody RequestImgDTO request) {
        Long userId = request.getUserId();
        String[] imageData = request.getImageData();

        List<String> images = Arrays.stream(imageData)
                .map(s -> s.replaceAll("[\"\\[\\]]", ""))
                .collect(Collectors.toList());

        User user = userService.selectUserByUserId(userId);
        if (user != null) {
            if (user.getToken() > 0) {
                user.setToken(user.getToken() - 1);
                TextInResult textInResult = textInService.photoToPdf(images, userId);
                return textInResult.getCode() == 200 && userService.updateUser(user) == 1 ? Result.ok(textInResult.getData()) :
                        Result.fail(textInResult.getCode(), textInResult.getMessage());
            } else {
                return Result.fail("调用次数不足");
            }
        }
        return Result.fail("用户不存在");
    }

    @ApiOperation(value = "WORD转JPG", notes = "将WORD文件转换为JPG文件, 文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("word-to-image")
    public Result wordToImg(@RequestBody RequestDTO request) {
        return PdfDeal(request, "wordToImg");
    }

    @ApiOperation(value = "图片转换word", notes = "将Base64编码的图片数据转换成Word文档")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/photo_to_word")
    public Result PhotoTOWord(@RequestBody RequestDTO request) {
        return PdfDeal(request, "imgToWord");
    }


    @ApiOperation(value = "历史记录", notes = "查看该用户的所有历史转换记录")
    @GetMapping("/history_file")
    public Result historyFile(@ApiParam(name = "userId", value = "用户ID", required = true) Long userId) {
        return userService.selectUserByUserId(userId) != null ? Result.ok(textInService.selectHistoryFile(userId)) :
                Result.fail("用户不存在");
    }

    @ApiOperation(value = "删除历史记录", notes = "删除该用户的历史转换记录")
    @GetMapping("/delete_history_file")
    public Result deleteHistoryFile(@ApiParam(name = "userId", value = "用户ID", required = true) Long userId) {
        if (userService.selectUserByUserId(userId) != null) {
            return textInService.deleteHistoryFile(userId) == 1 ? Result.ok("历史记录删除成功") :
                    Result.fail("删除失败");
        }
        return Result.fail("用户不存在");

    }


}
